/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 *
 * PartnerInfoServiceImpl.java
 */
package com.yixun.qfbao.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.yixun.common.page.Page;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import com.yixun.qfbao.mapper.ChannelRoleMapper;
import com.yixun.qfbao.mapper.CompanyRelationMapper;
import com.yixun.qfbao.mapper.DepartmentMapper;
import com.yixun.qfbao.mapper.DictionaryMapper;
import com.yixun.qfbao.mapper.PartnerInfoAdditionMapper;
import com.yixun.qfbao.mapper.PartnerInfoMapper;
import com.yixun.qfbao.mapper.ValidateCodeMapper;
import com.yixun.qfbao.model.ChannelRole;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.CompanyRelation;
import com.yixun.qfbao.model.Department;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.ModelInfo;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.PartnerInfoAddition;
import com.yixun.qfbao.model.ThreadLocalContainer;
import com.yixun.qfbao.model.ValidateCode;
import com.yixun.qfbao.model.dto.ChannelRoleDto;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.CompanyRelationDto;
import com.yixun.qfbao.model.dto.DepartmentDto;
import com.yixun.qfbao.model.dto.DictionaryDto;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.model.dto.SmsHistoryDto;
import com.yixun.qfbao.model.enums.CheckStatusEnum;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.MechanismAccountTypeEnum;
import com.yixun.qfbao.model.enums.PartnerInfoEnum;
import com.yixun.qfbao.model.enums.RelationStatusEnum;
import com.yixun.qfbao.model.enums.SMSTypeEnum;
import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.service.CompanyRelationService;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.GetWeAppQrCodeService;
import com.yixun.qfbao.service.ModelInfoService;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.service.SmsHistoryService;
import com.yixun.qfbao.service.ValidateCodeService;
import com.yixun.qfbao.util.PasswordUtil;
import com.yixun.qfbao.util.RegexUtils;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.mapper.CaseMemberMapper;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.enums.PartnerStatusEnum;


/**
 * [文件名称]<br>
 * PartnerInfoServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 合作机构 service interface impl<br>
 * <br>
 * [修改记录]<br>
 * 2015-10-13 15:32:11 创建 陶俊代码生成器<br>
 *
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Service("partnerInfoService")
public class PartnerInfoServiceImpl implements PartnerInfoService, GetWeAppQrCodeService {
	private Logger logger = LoggerFactory.getLogger(PartnerInfoService.class);

	@Autowired
	private PartnerInfoMapper mapper;
	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private ChannelRoleMapper channelRoleMapper;
	@Autowired
	private CompanyRelationMapper companyRelationMapper;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private ValidateCodeService validateCodeService;
	@Autowired
	private SMSUtil smsUtil;
	@Autowired
	private CompanyRelationService companyRelationService;
	@Autowired
	private SmsHistoryService smsHistoryService;
	@Autowired
	private ValidateCodeMapper validateCodeMapper;
	@Autowired
	private DictionaryMapper dictionaryMapper;
//	@Autowired
//	private SmsSettingService smsSettingService;
//	@Autowired
//    private PremisesRelationService premisesRelationService;
	@Autowired
    private CaseMemberMapper caseMemberMapper;
	@Autowired
	private PartnerInfoAdditionMapper partnerInfoAdditionMapper;
	@Autowired
	ModelInfoService modelInfoService;

	@Value("${system.domain}")
	private  String domainName;
	

	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<PartnerInfo> getPageModel(PartnerInfoDto entity,int begin,int end){
		List<PartnerInfo> rows = mapper.list(entity,begin,end);
		if(rows!=null&&rows.size()>0){
			for (PartnerInfo partnerInfo:rows) {
				DepartmentDto department =  departmentMapper.selectDempNameById(partnerInfo.getDeptId());
				if(department!=null){
					partnerInfo.setDempName(department.getDepartmentName());
					partnerInfo.setPrincipalName(department.getPrincipalName());
				}
				if(partnerInfo.getUserRoleId()!=null){
					ChannelRole channelRole = channelRoleMapper.selectById(new Long(partnerInfo.getUserRoleId()));
					if(channelRole!=null){
						partnerInfo.setRoleName(channelRole.getRoleName());
					}
				}

			}
		}
		Integer total = mapper.count(entity);
	    Page<PartnerInfo> msr = new Page<PartnerInfo>(total, rows);
		return msr;
	}
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<PartnerInfoDto> getDtoPageModel(PartnerInfoDto entity,int begin,int end){
		List<PartnerInfoDto> rows = mapper.selectDtolist(entity,begin,end);
		if(rows!=null&&rows.size()>0){
			for (PartnerInfo partnerInfo:rows) {
				DepartmentDto department =  departmentMapper.selectDempNameById(partnerInfo.getDeptId());
				if(department!=null){
					partnerInfo.setDempName(department.getDepartmentName());
					partnerInfo.setPrincipalName(department.getPrincipalName());
				}
				if(partnerInfo.getUserRoleId()!=null){
					ChannelRole channelRole = channelRoleMapper.selectById(new Long(partnerInfo.getUserRoleId()));
					if(channelRole!=null){
						partnerInfo.setRoleName(channelRole.getRoleName());
					}
				}

			}
		}
		Integer total = mapper.selectDtoCount(entity);
		Page<PartnerInfoDto> msr = new Page<PartnerInfoDto>(total, rows);
		return msr;
	}
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<PartnerInfoDto> getMyPageModel2(PartnerInfoDto entity,int begin,int end){
		Integer total = mapper.countByHigherId(entity);
		List<PartnerInfoDto> rows = mapper.listByHigherId(entity,begin,end);
		if(rows!=null&&rows.size()>0){
			List<Long> roleIds = rows.stream()
					.filter(item -> Objects.nonNull(item.getUserRoleId()))
					.map(PartnerInfoDto::getUserRoleId)
					.collect(Collectors.toList());
			ChannelRoleDto channelRoleDto = new ChannelRoleDto();
			channelRoleDto.setRoleIds(roleIds);
			List<ChannelRole> channelRoleList = channelRoleMapper.selectListByDto(channelRoleDto);
			Map<Long, ChannelRole> channelRoleMap = channelRoleList.stream()
					.collect(Collectors.toMap(ChannelRole::getId, Function.identity()));
			for (PartnerInfo partnerInfo:rows) {
				if(Objects.nonNull(partnerInfo.getUserRoleId())){
					ChannelRole channelRole = channelRoleMap.get(partnerInfo.getUserRoleId());
					if(Objects.nonNull(channelRole)){
						partnerInfo.setRoleName(channelRole.getRoleName());
					}
				}
			}
		}
		Page<PartnerInfoDto> msr = new Page<PartnerInfoDto>(total, rows);
		return msr;
	}
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<PartnerInfoDto> getPageModelByHigherid(PartnerInfoDto entity,int begin,int end){
		Integer total = mapper.countByHigherId(entity);
		List<PartnerInfoDto> rows = mapper.listByHigherId(entity,begin,end);
		if(CollectionUtils.isNotEmpty(rows)){
			List<Long> roleIds = rows.stream()
					.filter(item -> Objects.nonNull(item.getUserRoleId()))
					.map(PartnerInfoDto::getUserRoleId)
					.collect(Collectors.toList());
			ChannelRoleDto channelRoleDto = new ChannelRoleDto();
			channelRoleDto.setRoleIds(roleIds);
			List<ChannelRole> channelRoleList = channelRoleMapper.selectListByDto(channelRoleDto);
			Map<Long, ChannelRole> channelRoleMap = channelRoleList.stream()
					.collect(Collectors.toMap(ChannelRole::getId, Function.identity()));
			for (PartnerInfo partnerInfo: rows) {
				if(Objects.nonNull(partnerInfo.getUserRoleId())){
					ChannelRole channelRole = channelRoleMap.get(partnerInfo.getUserRoleId());
					if(Objects.nonNull(channelRole)){
						partnerInfo.setRoleName(channelRole.getRoleName());
					}
				}
			}
		}
		Page<PartnerInfoDto> msr = new Page<PartnerInfoDto>(total, rows);
		return msr;
	}
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<PartnerInfo> getMyPageModel(PartnerInfoDto entity,int begin,int end){
		List<PartnerInfo> rows = mapper.myList(entity,begin,end);
		if(rows!=null&&rows.size()>0){
			for (PartnerInfo partnerInfo:rows) {
				Department department =  departmentMapper.selectById(partnerInfo.getDeptId());
				if(department!=null){
					partnerInfo.setDempName(department.getDepartmentName());
				}
				if(partnerInfo.getUserRoleId()!=null){
					ChannelRole channelRole = channelRoleMapper.selectById(new Long(partnerInfo.getUserRoleId()));
					if(channelRole!=null){
						partnerInfo.setRoleName(channelRole.getRoleName());
					}
				}

			}
		}
		Integer total = mapper.myCount(entity);
		Page<PartnerInfo> msr = new Page<PartnerInfo>(total, rows);
		return msr;
	}

	/**
     * 查询列表
     * @param entity 搜索条件
     * @return 分页记录
     */
    public List<PartnerInfo> selectListByDto(PartnerInfoDto entity){
        return mapper.selectListByDto(entity);
    }

    /**
     * 查询列表
     * @param entity 搜索条件
     * @return 分页记录
     */
    public List<PartnerInfo> selectWholeListByDto(PartnerInfoDto entity){
        return mapper.selectWholeListByDto(entity);
    }
	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<PartnerInfo> searchListByDto(PartnerInfoDto entity,int begin,int end){
		return mapper.searchListByDto(entity,begin,end);
	}
	
	/**
	 *  获取审核列表总数量
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public int countSearchCheckListByDto(PartnerInfoDto entity){
		 return mapper.countSearchCheckListByDto(entity);
	}
	 
	 /**
	 * 查询审核列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<PartnerInfo> searchCheckListByDto(PartnerInfoDto entity,int begin,int end){
		return mapper.searchCheckListByDto(entity,begin,end);
	}
	
	/**
	 * 查询总数
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public Integer searchListByDtoCount(PartnerInfoDto entity){
		return mapper.searchListByDtoCount(entity);
	}
	
	@Override
	public int clearOpenidByUserId(Long userId) {
		PartnerInfoDto partnerInfo = new PartnerInfoDto();
		partnerInfo.setId(userId);
		partnerInfo.setNullWxOpenid(true);
		partnerInfo.setUpdateTime(new Date());
		return this.update(partnerInfo);
	}
	
	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<PartnerInfo> selectMyListByDto(PartnerInfoDto entity,int begin,int end){
		return mapper.myList(entity, begin, end);
	}

	/**
	 * 查询单个
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public PartnerInfo selectByDto(PartnerInfoDto entity){
		return mapper.selectByDto(entity);
	}
	/**
	 * 查询单个
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<PartnerInfoDto> selectByDto2(PartnerInfoDto entity){
		return mapper.selectByDto2(entity);
	}/**
	 * 查询单个
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<PartnerInfoDto> selectByDto3(PartnerInfoDto entity){
		return mapper.selectByDto3(entity);
	}

	/**
	 * @param id 搜索条件
	 * @return 分页记录
	 */
	public PartnerInfo selectById(Long id){
		if(id!=null){
			return mapper.selectById(id);
		}
		return null;
	}
	
	/**
	 * 	根据分销的人员ID获取当前人员信息，会包含对应总代公司的companyUuid
	 * @param id 根据主键搜索
	 * @return 一行记录
	 */
	@Override
	public PartnerInfo selectByAgencyId(Long id) {
		if(id != null){
			return mapper.selectByAgencyId(id);
		}
		return null;
	}
	/**
	 * @param entity 新增记录的详细信息
	 * @return 新增行数
	 */
	public PartnerInfoDto create(PartnerInfoDto entity) {
		entity.setCreateTime(Calendar.getInstance().getTime());
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		if(!"99".equals(entity.getIsAdmin())) {
			entity.setIsAdmin("0");
		}
		// 没有审核状态，则添加默认值
		if(!StringUtil.isNotNull(entity.getCheckStatus())) {
			entity.setCheckStatus(CheckStatusEnum.NOT_REQUIRED.getNo());
		}
		mapper.add(entity);
//		entity.setId(((long)id));
		return entity;
	}

	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	public int update(PartnerInfoDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		if(!"99".equals(entity.getIsAdmin())) {
			entity.setIsAdmin("0");
		}
		return mapper.edit(entity);
	}

	/**
	 * @param entity 待删除的记录信息
	 * @return 删除行数
	 */
	public int destroy(PartnerInfoDto entity) {
		return mapper.del(entity);
	}

	/**
	 * @param entity 新增或更新
	 * @return 新增行数
	 */
	public int saveOrUpdate(PartnerInfoDto entity) {
		if(entity!=null&&entity.getId()!=null){
			entity.setUpdateTime(new Date());
			return update(entity);
		}else{
			entity.setCreateTime(new Date());
			entity.setUpdateTime(new Date());
			create(entity);
			return 1;
		}
	}

	/**
	 * @param entity 根据pojo搜索如果主键为空则返回它本身
	 * @return 一行记录或本身
	 */
	@Override
	public PartnerInfo selectBy(PartnerInfo entity) {
		if(entity!=null&&entity.getId()!=null){
			return mapper.selectById(entity.getId());
		}
		return entity;
	}

	/**
	 * @param entity 待删除的记录信息
	 * @return 删除行数
	 */
	public int count(PartnerInfoDto entity) {
		return mapper.count(entity);
	}

	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<PartnerInfo>  logining(PartnerInfoDto entity){
		return mapper.logining(entity);
	}

	@Override
	public List<Long> listGroupCompanyId(String domain, String companyUuid) {
		// 查询该域名下的公司（开发商及合作机构）
		List<Long> companyIds = Lists.newArrayList();
		Company devCompany = getCompanyByDomain(domain,companyUuid);
		if(devCompany == null){
			throw new TServerException("未查询到开发商");
		}
		companyIds.add(devCompany.getId());
		//查询开发商系下的所有的中介机构
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setDevCompany(devCompany.getId());
		List<CompanyRelation> listCompanyRelation = companyRelationMapper.selectListByDto(companyRelationDto);

		for(CompanyRelation c : listCompanyRelation){
			companyIds.add(c.getAgentCompany());
		}

		return companyIds;
	}

	@Override
	public List<Long> listGroupCompanyIdByCompanyId(Long companyId, boolean includeSelf) {
		List<Long> companyIds = Lists.newArrayList();
		Company devCompany = companyService.selectById(companyId);
		if(devCompany == null){
			throw new TServerException("未查询到开发商");
		}
		if(includeSelf){
			// 包含自身: 通过开发商查询分销公司.通过此条件判断是否要返回开发商本身
			companyIds.add(devCompany.getId());
		}

		//查询开发商系下的所有的中介机构
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setDevCompany(devCompany.getId());
		List<CompanyRelation> listCompanyRelation = companyRelationMapper.selectListByDto(companyRelationDto);

		for(CompanyRelation c : listCompanyRelation){
			companyIds.add(c.getAgentCompany());
		}

		return companyIds;
	}

	@Override
    public List<PartnerInfo> checkRepeat(PartnerInfoDto entity) {
		List<PartnerInfo> partnerInfos = Lists.newArrayList();
		List<PartnerInfo> temp = Lists.newArrayList();
		List<PartnerInfo> partnerInfoList = mapper.listPartnerInfoByCheckRepeat(entity);
        if(CollectionUtils.isNotEmpty(partnerInfoList)){
			logger.info("CheckRepeat partnerInfoList size is :" + partnerInfoList.size());
			temp.addAll(partnerInfoList);
		}
		List<PartnerInfo> partnerInfoByAdditionList = mapper.listPartnerInfoByAdditionCheckRepeat(entity);
		if(CollectionUtils.isNotEmpty(partnerInfoByAdditionList)){
			logger.info("CheckRepeat partnerInfoByAdditionList size is :" + partnerInfoByAdditionList.size());
			temp.addAll(partnerInfoList);
		}
		if(CollectionUtils.isNotEmpty(temp)){
			partnerInfos = temp.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PartnerInfo::getPhone))), ArrayList::new));
		}
		logger.info("CheckRepeat partnerInfos size is :" + partnerInfos.size());
        return partnerInfos;
    }

	@Override
	public List<PartnerInfoDto> selectAgentList(PartnerInfoDto entity) {
		return mapper.selectAgentList(entity);
	}

	
	
	@Override
	@Transactional(isolation= Isolation.SERIALIZABLE)
	public Map<String,String> bindPartner(PartnerInfoDto dto,String companyUuid){
		String domain = dto.getDomain();
		if(RegexUtils.domainRegex(dto.getDomain())){
			domain = dto.getDomain().substring(dto.getDomain().indexOf("//")+2,dto.getDomain().indexOf("."));
		}

		String registerPwd = dto.getRegisterPwd();
		Map<String,String> map = new HashMap<String, String>();
//		String sms = "注册成功";
		String msg = "注册成功";
		String result = "success";

		//根据域名获取公司信息
		Company company = getCompanyByDomain(domain,companyUuid);
		if(company == null){
			map.put("result","fail");
			map.put("msg","通过域名未查询到开发商");
			return map;
		}

		//验证客户重复性
		// todo 查询加上启用状态
		dto.setDevCompanyId(company.getId());
		List<PartnerInfo> list = getRegisterPartner(domain,dto.getPhone(),companyUuid);
		if(list != null && list.size() > 0){
			map.put("result","fail");
			map.put("msg","该手机号码已存在，请核实");
			return map;
		}

		//根据code查询公司-->获取公司id-->验证公司绑定开发商有效性
		CompanyRelationDto companyRelationDto = null;
		if(!StringUtils.isEmpty(dto.getCompanyCode())){
			companyRelationDto = companyRelationMapper.selectBindCompanyId(dto.getCompanyCode());
		}

		//整理数据，优先设置为游客（公司绑定到开发商,userRoleId 设置为0）
		dto = setPartnerInfoDto(dto);
		String pwd;
		if(StringUtils.isBlank(registerPwd)){
			pwd = PasswordUtil.generateRandomPwd(8);
		}else {
			pwd = registerPwd;
		}
		dto.setPassword(PasswordUtil.md5Hex(pwd));

		if(companyRelationDto != null && companyRelationDto.getDevCompany() != null){
			if(company.getId().equals(companyRelationDto.getDevCompany())){//该开发商与与中介机构存在绑定关系
				//设置部门id
				if(null == dto.getDeptId()) {
					DepartmentDto departmentDto = new DepartmentDto();
					departmentDto.setParentId(0l);
					departmentDto.setMerchantId(companyRelationDto.getAgentCompany());
					departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					Department department = departmentMapper.selectByDto(departmentDto);
					dto.setDeptId(department.getId());
				}
				dto.setHigherid(companyRelationDto.getAgentCompany());//设置中介机构
				dto.setUserRoleId(Long.valueOf(PartnerInfoEnum.NO_ROLER.getCode()));//无角色
				msg = "绑定成功";
			}else{
				dto.setHigherid(company.getId());//绑定在该开发商下(否则用户区分不了开发商)
			}
		}

		// 注册
		dto.setIsAdmin("0");
		if(!StringUtil.isNotNull(dto.getCheckStatus())) {
			dto.setCheckStatus(CheckStatusEnum.NOT_REQUIRED.getNo());
		}
		int id = mapper.add(dto);
		if(id == 0){
			result = "fail";
			msg = "注册失败";
		}else if(!SystemIdEnum.WEAPP_AGENCY.getCode().equals(dto.getSystemId()) && id > 0){
			//设置短信无效
			// 分销小程序不需要下发短信。 update by liu.zilong
			validateCodeService.deleteValidate(dto.getPhone());
			String messageContent = "【分销助手】您已注册成功，您的初始密码为:" + pwd + "，请及时修改！";

			//获取短信设置,功能已变更.设置已用于定制化号码验真.此处不能保留
			Map<String, String> smsSettingMap = null;
//        	Map<String, String> smsSettingMap = smsSettingService.getSmsSettingMap(null, company.getId(),null);
        	Map<String,String> qfSmsMap = new HashMap<>();
        	qfSmsMap.put("key1",pwd);
			Map<String, Object> returnMap = smsUtil.sendMessage(messageContent,dto.getPhone(), QfSmsTemplateEnum.SMS_REGISTER_SUCCESS.getId(), smsSettingMap,qfSmsMap);
			boolean sendStatus = (Boolean) returnMap.get("sendStatus");
			String sendRes = String.valueOf(returnMap.get("sendRes"));
			//添加进历史表
			SmsHistoryDto history = new SmsHistoryDto();
			history.setContent(messageContent);
			history.setReceiver(dto.getPhone());
			if(company !=null && company.getId() != null){
				history.setMerchantId(company.getId());
			}else{
				history.setMerchantId(0L);
			}
			history.setSender("qiaofang");
//			if(null != smsSettingMap) {
//				history.setSender(smsSettingMap.get("userName"));
//			}
			history.setRemark(SMSTypeEnum.TYPE_13.getDes());
			history.setCreateTime(new Date());
			history.setCreateUserId(0l);
			if(sendStatus){
				logger.info(messageContent);
				history.setSendStatus(SendStatusEnum.SUCCESS.getNo());
			}else{
				history.setSendStatus(SendStatusEnum.FAILURE.getNo());
			}
			history.setSendRes(sendRes);
			if(returnMap.containsKey("orderUuid")){
				history.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
			}
			if(returnMap.containsKey("platform")){
				history.setPlatform(String.valueOf(returnMap.get("platform")));
			}
			smsHistoryService.create(history);
		}else {
			ThreadLocalContainer.Regesiter.USER_ID.set(dto.getId());
			// add by zilong.liu 分销小程序需要添加对应的模板信息
			List<ModelInfo> modelInfoList = ThreadLocalContainer.Regesiter.MODEL_INFO_LIST.get();
			if (!CollectionUtils.isEmpty(modelInfoList)) {
				for (ModelInfo modelInfo : modelInfoList) {
					modelInfo.setRelId(dto.getId());
					modelInfo.setCreateUserId(String.valueOf(dto.getId()));
				}
				// 批量插入模板信息集合
				modelInfoService.batchInsertModelInfo(modelInfoList);
			}
			// add by zilong.liu 分销小程序需要添加对应的模板信息
		}

		map.put("result",result);
		map.put("msg",msg);

		return map;
	}

	/**
	 *  根据系统类型查询相应的用户信息
	 * @param domain
	 * @return
	 */
	@Override
	public List<PartnerInfo> getRegisterPartner(String domain,String phone,String systemId,String companyUuid){
		// 查询该域名下的公司（开发商及合作机构）
		List<Long> companyIds = new ArrayList<Long>();
		//1 获取开发商
		if(StringUtils.isEmpty(companyUuid)){
			if(StringUtils.isEmpty(domain)){
				throw new TServerException("域名信息为空");
			}
			if(RegexUtils.domainRegex(domain)){
				domain = domain.substring(domain.indexOf("//")+2,domain.indexOf("."));
			}
		}

		Company devCompany = getCompanyByDomain(domain,companyUuid);
		if(devCompany == null){
			throw new TServerException("未查询到开发商");
		}

		if(SystemIdEnum.DEVELOPERS.getCode().equals(systemId) || SystemIdEnum.ASSISTANT.getCode().equals(systemId) || SystemIdEnum.APP_ASSISTANT.getCode().equals(systemId)){
			companyIds.add(devCompany.getId());
		}else if(SystemIdEnum.AGENCY_h5.getCode().equals(systemId)||SystemIdEnum.WEAPP_AGENCY.getCode().equals(systemId) || SystemIdEnum.AGENCY_WEB.getCode().equals(systemId) || SystemIdEnum.APP_AGENCY.getCode().equals(systemId)){
			//查询开发商系下的所有的中介机构
			CompanyRelationDto companyRelationDto = new CompanyRelationDto();
			companyRelationDto.setDevCompany(devCompany.getId());
			List<CompanyRelation> listCompanyRelation = 	companyRelationMapper.selectListByDto(companyRelationDto);

			for(CompanyRelation c : listCompanyRelation){
				companyIds.add(c.getAgentCompany());
			}
		}

		//既包含开发商，又包含中介机构
		PartnerInfoDto selectDto = new PartnerInfoDto();
		selectDto.setCompanyIds(companyIds);
		selectDto.setPhone(phone);
		selectDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		selectDto.setStatus(PartnerInfoEnum.STATUS_ENABLE.getCode());//所有启用状态的
		/** 旧方法，关联子查询会造成慢sql */
		// return mapper.checkRepeat(selectDto);
		return mapper.listPartnerInfoByCheckRepeat(selectDto);
	}


	/**
	 *  获取某个域名下的所有已注册的用户
	 * @param domain
	 * @return
	 */
	@Override
	public List<PartnerInfo> getRegisterPartner(String domain,String phone,String companyUuid){
		// 查询该域名下的公司（开发商及合作机构）
		List<Long> companyIds = new ArrayList<Long>();
		Company devCompany = getCompanyByDomain(domain,companyUuid);
		if(devCompany == null){
			throw new TServerException("未查询到开发商");
		}
		companyIds.add(devCompany.getId());
		//查询开发商系下的所有的中介机构
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setDevCompany(devCompany.getId());
		List<CompanyRelation> listCompanyRelation = companyRelationMapper.selectListByDto(companyRelationDto);

		for(CompanyRelation c : listCompanyRelation){
			companyIds.add(c.getAgentCompany());
		}
		//既包含开发商，又包含中介机构
		PartnerInfoDto selectDto = new PartnerInfoDto();
		selectDto.setCompanyIds(companyIds);
		selectDto.setPhone(phone);
		List<PartnerInfo> piList = checkRepeat(selectDto);
		return piList;
	}

	/**
	 * 删除用户
	 * @param info
	 * @return
	 */
	public int deletePartnerInfo(PartnerInfo info){
		PartnerInfoDto dto = new PartnerInfoDto();
		dto.setId(info.getId());
		dto.setDelFlag(DelFlagEnum.DEL.getNo());
		dto.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edit(dto);
	}

	/**
	 * 重置密码
	 * @author sangtao
	 * @param partnerInfo
	 * @return
	 */
	@Override
	public boolean resetPasswordByValidate(PartnerInfoDto partnerInfo,String companyUuid){
		if(RegexUtils.domainRegex(partnerInfo.getDomain())){
			partnerInfo.setDomain(partnerInfo.getDomain().substring(partnerInfo.getDomain().indexOf("//")+2,partnerInfo.getDomain().indexOf(".")));
		}
		boolean flag = isValidate(partnerInfo.getPhone(),partnerInfo.getVerificationCode(),partnerInfo.getDomain(),partnerInfo.getSystemId(),companyUuid);
		//验证成功
		if(flag){
			PartnerInfo user = getPartnerInfo(partnerInfo.getDomain(),partnerInfo.getPhone(),partnerInfo.getSystemId(),companyUuid);
			if(user != null){
				PartnerInfoDto editInfo = new PartnerInfoDto();
				editInfo.setId(user.getId());
				editInfo.setPassword(PasswordUtil.md5Hex("x1234567"));
				update(editInfo);
				return true;
			}else{
				throw  new TServerException("账号不存在或已禁用");
			}
		}else{
			throw  new TServerException("验证码错误");
		}
	}

	//根据域名查询公司
	private Company getCompanyByDomain(String domain,String companyUuid){
		CompanyDto cDto = new CompanyDto();
		// todo 审核条件去掉
		//cDto.setStatus("1");//审核状态：0待审核1审核通过2审核失败
		if(StringUtils.isNotEmpty(companyUuid)){
			cDto.setCompanyUuid(companyUuid);
		}else{
			cDto.setDomain(domain);

		}
		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<Company> lists = companyService.selectListByDto(cDto);
		if(lists.size() > 0){
			return lists.get(0);
		}else{
			return null;
		}
	}

	private PartnerInfoDto setPartnerInfoDto(PartnerInfoDto dto){
		dto.setUserRoleId(Long.valueOf(PartnerInfoEnum.TOURIST_ROLE.getCode()));
//		dto.setPassword(PasswordUtil.md5Hex(PasswordUtil.DEFAULT_PWD));
		dto.setAccountType(PartnerInfoEnum.ACCOUNT_INDIVIDUAL.getCode());//非管理员
		dto.setStatus(PartnerInfoEnum.STATUS_ENABLE.getCode());//启用状态
		dto.setDelFlag(PartnerInfoEnum.DEL_FLAG_TRUE.getCode());
		dto.setHigherid(dto.getDevCompanyId());//游客先插入开发商的id
		dto.setCreateTime(Calendar.getInstance().getTime());
		dto.setUpdateTime(Calendar.getInstance().getTime());
		return dto;
	}
	@Override
	public int delPartnerByDeptId(Long deptId) {
		return mapper.delPartnerByDeptId(deptId);
	}


	private boolean isValidate(String phone,String code,String domain,String systemId,String companyUuid){
		//取最新 的那一条
		boolean flag = false;
		List<ValidateCode> list = validateCodeMapper.selectForPwd(phone,systemId,domain,companyUuid);
		if(list != null && list.size() > 0){
			if(list.get(0).getValidateCode().equals(code)){
				flag = (System.currentTimeMillis() - (list.get(0).getCreateTime()).getTime()) / 1000 < 180;
				if(!flag){
					throw new TServerException("验证码已过期，请重新获取");
				}
			}
		}
		return flag;
	}
	/**
	 * 根据域名查询用户是否存在
	 * @author sangtao
	 * @param domain
	 * @param phone
	 * @return
	 */
	private PartnerInfo getPartnerInfo(String domain,String phone,String systemId,String companyUuid){
		List<PartnerInfo> list =  getRegisterPartner(domain,phone,systemId, companyUuid);
		if(list != null && list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}

	@Override
	public PartnerInfo checkPhoneByDomain(PartnerInfoDto partnerInfoDto,String commpanyUuid) {
		List<PartnerInfo> list =  getRegisterPartner(partnerInfoDto.getDomain(),partnerInfoDto.getPhone(),partnerInfoDto.getSystemId(),commpanyUuid);
		if(list != null && list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updatePassword(Long userId,String oldPassword,String newPassword,String cofirmPassword) throws Exception {
		if(userId==null){
			throw new TServerException("用户id为空");
		}
		PartnerInfo info = mapper.selectById(userId);
		if(!PasswordUtil.md5Hex(oldPassword).equals(info.getPassword())){
			throw new TServerException("原密码错误");
		}

		if(PasswordUtil.md5Hex(newPassword).equals(info.getPassword())){
			throw new TServerException("新密码不能跟原密码相同");
		}

		if(!newPassword.equals(cofirmPassword)){
			throw new TServerException("新密码不一致");
		}
		PartnerInfoDto infodto=new PartnerInfoDto();
		org.springframework.beans.BeanUtils.copyProperties(info, infodto);
		infodto.setPassword(PasswordUtil.md5Hex(cofirmPassword));
		if(mapper.edit(infodto) <= 0){
			throw new TServerException("修改密码失败");
		}
		//密码修改成功,短信提醒
		//判断短信开发是否开启
		String smsSwitch = smsUtil.getSmsSwitch();
		if(org.apache.commons.lang.StringUtils.isNotEmpty(smsSwitch) && "T".equals(smsSwitch)){
			//获取短信模板
			String smsTemp = SMSTypeEnum.TYPE_12.getNo();
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDicType(smsTemp);
			Dictionary dic = dictionaryMapper.selectByDto(dicDto);
			if(null != dic){
				String cusName = info.getAccountName();
				String mobile = info.getPhone();
				Long companyId = null;
				String smsContent = dic.getDicValue();
				smsContent = String.format(smsContent, cusName, newPassword);
				//获取开发商
                Company company = companyService.selectById(companyId);
                if(null != company && StringUtils.isNotBlank(company.getDomain())) {
                	companyId = company.getId();
                }else {
                	CompanyRelationDto crDto = new CompanyRelationDto();
					crDto.setAgentCompany(companyId);
					crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
					List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
					if(null != crList && crList.size() > 0){
						CompanyRelation cr = crList.get(0);
						companyId = cr.getDevCompany();
					}
                }
				//获取短信设置,功能已变更.设置已用于定制化号码验真.此处不能保留
				Map<String, String> smsSettingMap = null;
//            	Map<String, String> smsSettingMap = smsSettingService.getSmsSettingMap(null, companyId,null);
				//发送短信
				//营销号短信
				Map<String,String> qfSmsMap = new HashMap<>();
				qfSmsMap.put("key1",cusName);
				qfSmsMap.put("key2",newPassword);

				Map<String, Object> returnMap = smsUtil.sendMessage(smsContent, mobile, QfSmsTemplateEnum.SMS_RESET_PWD.getId(), smsSettingMap,qfSmsMap);
				boolean sendStatus = (Boolean) returnMap.get("sendStatus");
				String sendRes = String.valueOf(returnMap.get("sendRes"));
				//保存短信历史信息
				SmsHistoryDto smsHis = new SmsHistoryDto();
				smsHis.setSender(smsUtil.getUserName());
//				if(null != smsSettingMap) {
//    				smsHis.setSender(smsSettingMap.get("userName"));
//    			}
				smsHis.setReceiver(mobile);
				smsHis.setContent(smsContent);
				smsHis.setSendStatus(sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
				smsHis.setSendRes(sendRes);
				smsHis.setMerchantId(companyId);
				smsHis.setRemark("修改密码: 用户修改密码");
				smsHis.setCreateUserId(info.getId());
				if(returnMap.containsKey("orderUuid")){
					smsHis.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
				}
				if(returnMap.containsKey("platform")){
					smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
				}
				smsHistoryService.create(smsHis);
			}
		}
	}

	/**
	*@description 人员转移部门
	*@author sangtao
	*@date 2017/12/15
	*@param id
	*@param deptId
	**/
	@Override
	public Boolean changePartnerDept(Long id,Long deptId){
		try{
			PartnerInfo partnerInfo = new PartnerInfo();
			partnerInfo.setId(id);
			partnerInfo.setDeptId(deptId);
			mapper.edit(partnerInfo);
			return true;
		}catch (Exception e){
			return false;
		}
	}

    @Override
    public List<PartnerInfo> getRegisterPartnerByCondition(String domain, String phone, String companyUuid) {
        // 查询该域名下的公司（开发商及合作机构）
        List<Long> companyIds = new ArrayList<Long>();
        if (StringUtils.isEmpty(companyUuid) && StringUtils.isEmpty(domain)) {
            throw new TServerException("获取公司uuid失败");
        }
        CompanyDto cDto = new CompanyDto();
        cDto.setDomain(domain);
        cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
        cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        cDto.setCompanyUuid(companyUuid);
        Company devCompany = companyService.selectByDto(cDto);
        //Company devCompany = getCompanyByDomain(domain);
        if (devCompany == null) {
            throw new TServerException("未查询到开发商");
        }
        companyIds.add(devCompany.getId());
        //查询开发商系下的所有的中介机构
        CompanyRelationDto companyRelationDto = new CompanyRelationDto();
        companyRelationDto.setDevCompany(devCompany.getId());
        List<CompanyRelation> listCompanyRelation = companyRelationMapper.selectListByDto(companyRelationDto);

        for (CompanyRelation c : listCompanyRelation) {
            companyIds.add(c.getAgentCompany());
        }
        //既包含开发商，又包含中介机构
        PartnerInfoDto selectDto = new PartnerInfoDto();
        selectDto.setCompanyIds(companyIds);
        selectDto.setPhone(phone);
        return checkRepeat(selectDto);
    }

	/**
	 * 根据经济公司查询手机号是否存在账号
	 * @param phone
	 * @param agentCompany
	 * @return
	 */
	public List<PartnerInfo> getRegisterPartnerByAgentCompany(String phone,Long agentCompany){
		List<Long> companyIds = new ArrayList<Long>();
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		companyRelationDto.setAgentCompany(agentCompany);
		List<CompanyRelation> companyRelations = companyRelationService.selectListByDto(companyRelationDto);
		if(null == companyRelations || companyRelations.size() == 0){
			throw new RuntimeException("该渠道下不存在经济公司");
		}
		companyIds.add(companyRelations.get(0).getDevCompany());

		CompanyRelationDto listDto = new CompanyRelationDto();
		listDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		listDto.setDevCompany(companyRelations.get(0).getDevCompany());
		List<CompanyRelation> listCompanyRelation = companyRelationMapper.selectListByDto(listDto);
		for(CompanyRelation c : listCompanyRelation){
			companyIds.add(c.getAgentCompany());
		}

		//既包含开发商，又包含中介机构
		PartnerInfoDto selectDto = new PartnerInfoDto();
		selectDto.setCompanyIds(companyIds);
		selectDto.setPhone(phone);
		return checkRepeat(selectDto);
	}
	public String getDomainName() {
		return domainName;
	}

    @Override
    public List<PartnerInfoDto> selectStaffListByDto(PartnerInfoDto partnerInfoDto) {
        return mapper.selectStaffListByDto(partnerInfoDto);
    }

    @Override
    public List<PartnerInfoDto> selectPrincipalListByDto(PartnerInfoDto partnerInfoDto) {
        return mapper.selectPrincipalListByDto(partnerInfoDto);
    }

    /**
     * 获取楼盘指定分销机构的所有经纪人
     * @return
     */
    public List<String> selectOpenIdByAssign(Long premiseId) {
	    List<String> openIdList = new ArrayList<>();

        List<PartnerInfoDto> list = mapper.selectOpenIdByAssign(premiseId);
        if(list == null) {
            return null;
        }
        openIdList = list.stream().filter(partnerInfoDto -> partnerInfoDto.getWxOpenid() != null)
                .map(PartnerInfo::getWxOpenid).collect(Collectors.toList());

	    return openIdList;
    }

	/**
	 * 根据公司id获取相应人员
	 * @param companyIds
	 * @return
	 */
	@Override
	public List<String> getPartnersByCompanyIds(List<String> companyIds){
		List<String> openIdList = new ArrayList<>();
    	PartnerInfoDto dto = new PartnerInfoDto();
    	dto.setHigherIds(companyIds);

    	if(companyIds == null || companyIds.size() == 0){
    		return  new ArrayList<>();
		}

    	List<PartnerInfoDto> partnerInfoList = mapper.selectPartnerByCompanyIds(dto);
		openIdList = partnerInfoList.stream().filter(partnerInfoDto -> partnerInfoDto.getWxOpenid() != null)
				.map(PartnerInfo::getWxOpenid).collect(Collectors.toList());

		return openIdList;
	}

	/**
	 * 根据公司id获取相应人员
	 * @param companyIds
	 * @return
	 */
	@Override
	public List<String> getPartnersAdminByCompanyIds(List<String> companyIds){
		List<String> openIdList = new ArrayList<>();
		PartnerInfoDto dto = new PartnerInfoDto();
		dto.setHigherIds(companyIds);

		if(companyIds == null || companyIds.size() == 0){
			return  new ArrayList<>();
		}

		List<PartnerInfoDto> partnerInfoList = mapper.selectPartnerByCompanyIds(dto);
		openIdList = partnerInfoList.stream().filter(partnerInfoDto -> partnerInfoDto.getWxOpenid() != null && MechanismAccountTypeEnum.mechanism.getNo().equals(partnerInfoDto.getAccountType()))
				.map(PartnerInfo::getWxOpenid).collect(Collectors.toList());

		return openIdList;
	}

	/**
	 * 根据楼盘获取驻场人员
	 * @param premisesId
	 * @return
	 */
	@Override
	public List<String> getCaseMemberByPremises(Long premisesId){
		List<String> openIdList = new ArrayList<>();

		List<PartnerInfoDto> partnerInfoDtoList = mapper.selectCaseMemberByPremises(premisesId);
		openIdList = partnerInfoDtoList.stream().filter(partnerInfoDto -> partnerInfoDto.getWxOpenid() != null)
				.map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
		return openIdList;
	}

    /**
     * 获取代报备人openId
     * @param partnerId
     * @return
     */
	public String getReplaceReporterOpenId(List<PartnerInfo> reveivePartnerInfos, Long partnerId) {
        // 判断该代报备人是否为驻场人员且微信模板消息为可接收状态
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPartnerId(partnerId);
        List<CaseMemberDto> caseMemberList = caseMemberMapper.selectListForWxMsg(caseMemberDto);
        if(null != caseMemberList && caseMemberList.size() > 0) {
            boolean hasCaseMember = "1".equals(caseMemberList.get(0).getWxMsgStatus());
            if(!hasCaseMember) {
                return null;
            }
            Long pId = hasCaseMember ? caseMemberList.get(0).getPartnerId() : partnerId;
            PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
            partnerInfoDto.setId(pId);
            partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
            partnerInfoDto.setStatus(PartnerStatusEnum.VALID.getNo());
            PartnerInfo partnerInfo = mapper.selectByDto(partnerInfoDto);
            if(partnerInfo != null) {
            	reveivePartnerInfos.add(partnerInfo);
            }
            return partnerInfo == null ? null : partnerInfo.getWxOpenid();
        } else {
            // 如果为空则判断代报备人是否为超级管理员
            // 获取人员openId
            PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
            partnerInfoDto.setId(partnerId);
            partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
            partnerInfoDto.setStatus(PartnerStatusEnum.VALID.getNo());
            PartnerInfo partnerInfo = mapper.selectByDto(partnerInfoDto);
            if(partnerInfo != null) {
            	reveivePartnerInfos.add(partnerInfo);
            }
            return (partnerInfo != null && partnerInfo.getAccountType() != null && "0".equals(partnerInfo.getAccountType()))
                    ? partnerInfo.getWxOpenid() : null;
        }
    }

    @Override
    public List<PartnerInfoAddition> listPartnerInfoAddition(Long id) {
        return partnerInfoAdditionMapper.listPartnerInfoAddition(id);
    }

    @Override
    public void addPartnerInfoAddition(PartnerInfoAddition partnerInfoAddition) {
        partnerInfoAdditionMapper.addPartnerInfoAddition(partnerInfoAddition);
    }

    @Override
    public void addPartnerInfoAdditionWithoutPhone(PartnerInfoAddition partnerInfoAddition) {
        partnerInfoAdditionMapper.addPartnerInfoAdditionWithoutPhone(partnerInfoAddition);
    }

    @Override
    public List<PartnerInfo> listPartnerInfoForLogin(PartnerInfoDto partnerInfoDto) {
		/** 旧方法，关联子查询会造成慢sql */
        //return mapper.listPartnerInfoForLogin(partnerInfoDto);
		List<PartnerInfo> partnerInfoList =  mapper.listPartnerInfo(partnerInfoDto);
		List<PartnerInfo> partnerInfoAdditionList =  mapper.listPartnerInfoByAddition(partnerInfoDto);
		List<PartnerInfo> partnerInfos = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(partnerInfoList)){
			logger.info("ListPartnerInfoForLogin find size: "+  partnerInfoList.size());
			partnerInfos = partnerInfoList;
		}
		if(CollectionUtils.isNotEmpty(partnerInfoAdditionList)){
			logger.info("ListPartnerInfoForLoginAddition find size: "+  partnerInfoAdditionList.size());
			partnerInfos.addAll(partnerInfoList);
		}
		logger.info("ListPartnerInfoForLoginResponse find size: "+  partnerInfos.size());
		return partnerInfos;
    }

    @Override
    public PartnerInfo getPartnerInfoForLogin(PartnerInfoDto partnerInfoDto) {
		/** 旧方法，关联子查询会造成慢sql */
        // return mapper.getPartnerInfoForLogin(partnerInfoDto);
		PartnerInfo pi = mapper.getPartnerInfo(partnerInfoDto);
		logger.info("GetPartnerInfoForLogin phone "+  partnerInfoDto.getPhone());
		if(pi == null){
			List<PartnerInfo> piList = mapper.listPartnerInfoByAddition(partnerInfoDto);
			if(CollectionUtils.isNotEmpty(piList)){
				pi = piList.get(0);
				logger.info("GetPartnerInfoForLogin PartnerInfo is null "+  partnerInfoDto.getPhone() + "PartnerInfoAddition size" + piList.size());
			}
		}
		return pi;
    }

	@Override
	public List<PartnerInfoDto> listPartnerInfoByDeptIds(List<Long> deptIds) {
		return mapper.listPartnerInfoByDeptIds(deptIds);
	}

	@Override
	public List<Long> listPartnerInfoIdByDeptIds(List<Long> deptIds) {
		List<Long> ids = Lists.newArrayList();
		List<PartnerInfoDto> partnerInfos = mapper.listAllPartnerInfoByDeptIds(deptIds);
		if (partnerInfos != null && partnerInfos.size() > 0) {
			for (PartnerInfoDto info : partnerInfos) {
				ids.add(info.getId());
			}
		}
		return ids;
	}

	@Override
	public void adminTransfer(PartnerInfoDto oldAdmin, PartnerInfoDto newAdmin) throws Exception {
		if (oldAdmin.getId() == 0) {
			throw new Exception("新的管理员id不能为空");
		}
		if (newAdmin.getId() == 0) {
			throw new Exception("旧的管理员id不能为空");
		}
		//取消旧的管理员
		mapper.adminTransfer(newAdmin);

		//设置新的管理员
		mapper.adminTransfer(oldAdmin);
	}
	
	
	/**
	 * 设置分销用户权限
	 * 	如果是管理员，则设置为
	 * @param oldAdmin
	 * @param newAdmin
	 * @throws Exception
	 */
	@Override
	public String setAgencyAccountType(PartnerInfoDto partnerInfoDto) {
		mapper.adminTransfer(partnerInfoDto);
		return "succ";
	}
	
	/**
	 *     根据员工ID查询员工名称+wxopenid + 公司，组别，部门信息
	 * @param staffIdList
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getPartenerInfo(List<Object> staffIdList) {
		return mapper.getPartenerInfo(staffIdList);
	}

	/**
	 *   根据微信openId，判断是否要进行隐藏号码展示
	 * @param wxOpenIds
	 * @return
	 */
	@Override
	public List<String> getPhoneHideByOpenId(List<String> wxOpenIds){
		return mapper.getPhoneHideByOpenId(wxOpenIds);
	}
	
	/**
	 *  根据员工的手机号以及公司UUID获取所有员工的信息
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getAllPartnerInfoByPhoneAndCompany(Map<String, Object> phoneAndCompanyInfo) {
		return mapper.getAllPartnerInfoByPhoneAndCompany(phoneAndCompanyInfo);
	}

	@Override
	public List<String> getHideAgentPhoneOpenIds(List<String> wxOpenIds) {
		return mapper.getHideAgentPhoneOpenIds(wxOpenIds);
	}
	
	/**
	 * 获取个人的分销小程序推广码
	 */
	@Override
	public String getWeAppQrCodeUrl(String userId, Long deptId, String... strategy) {
		PartnerInfo partnerInfo = mapper.selectById(Long.valueOf(userId));
		return partnerInfo.getPersonalCardQrcode();
	}
	
	/**
	 * 获取微信携带的参数
	 */
	@Override
	public String getWeAppScene(String userId, Long id, String companyUuid, String... strategy) {
		return userId;
	}
	
	/**
	 * 保存生产的二维码
	 */
	@Override
	public int saveQrCodeUrl(String userId, Long deptId, String qrCodeUrl, String... strategy) {
		PartnerInfo partnerInfo = new PartnerInfo();
		partnerInfo.setId(Long.parseLong(userId));
		partnerInfo.setPersonalCardQrcode(qrCodeUrl);
		partnerInfo.setUpdateTime(new Date());
		return mapper.edit(partnerInfo);
	}
	
}
